#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int left = 0, right = arr.size()-1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] > x)
                right = mid - 1;
            else
                left = mid + 1;
        }
        swap(left, right);
        while (k > 0) {
            int leftD = INT32_MAX, rightD = INT32_MAX;
            if(left>=0)
                leftD = abs(arr[left]-x);
            if (right < arr.size())
                rightD = abs(arr[right] - x);
            if (leftD <= rightD)
                left--;
            else
                right++;
            --k;
        }
        vector<int>res(arr.begin() + left + 1, arr.begin() + right);
        return res;
    }
};